document.addEventListener('DOMContentLoaded', function() {
  // 登录相关元素
  const loginSection = document.getElementById('loginSection');
  const mainSection = document.getElementById('mainSection');
  const usernameInput = document.getElementById('username');
  const passwordInput = document.getElementById('password');
  const loginBtn = document.getElementById('loginBtn');
  const registerBtn = document.getElementById('registerBtn');
  const loginStatus = document.getElementById('loginStatus');
  const userWelcome = document.getElementById('userWelcome');
  const logoutBtn = document.getElementById('logoutBtn');
  
  // 功能相关元素
  const bookmarkBtn = document.getElementById('bookmarkBtn');
  // const viewBtn = document.getElementById('viewBtn');
  const statusDiv = document.getElementById('status');
  const recentBookmarksList = document.getElementById('recentBookmarks');

  // 标签页相关元素
  const tabBookmarks = document.getElementById('tabBookmarks');
  const tabClosedTabs = document.getElementById('tabClosedTabs');
  const tabBookmarksContent = document.getElementById('tabBookmarksContent');
  const tabClosedTabsContent = document.getElementById('tabClosedTabsContent');
  const recentClosedTabsList = document.getElementById('recentClosedTabs');

  const logoBtn = document.getElementById('logo');


  const baseUrl = 'http://localhost:8080';
  
  // 通用网络请求方法
  function makeRequest(url, method, data, headers = {}) {
    const defaultHeaders = {
      'Content-Type': 'application/json',
    };
    
    const requestOptions = {
      method: method,
      headers: { ...defaultHeaders, ...headers },
    };
    
    if (data && (method === 'POST' || method === 'PUT')) {
      requestOptions.body = JSON.stringify(data);
    }
    
    return fetch(url, requestOptions)
      .then(response => {
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        return response.json();
      });
  }
  
  // 初始化标签页切换
  initTabs();
  
  // 检查登录状态
  checkLoginStatus();
  
  // 登录按钮事件
  loginBtn.addEventListener('click', function() {
    const username = usernameInput.value.trim();
    const password = passwordInput.value.trim();
    
    if (!username || !password) {
      showLoginStatus('请输入用户名和密码', 'error');
      return;
    }
    
    login(username, password);
  });
  
  // 注册按钮事件
  registerBtn.addEventListener('click', function() {
    const username = usernameInput.value.trim();
    const password = passwordInput.value.trim();
    
    if (!username || !password) {
      showLoginStatus('请输入用户名和密码', 'error');
      return;
    }
    
    register(username, password);
  });
  
  // 退出按钮事件
  logoutBtn.addEventListener('click', function() {
    logout();
  });
  
  // 回车键登录
  passwordInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
      loginBtn.click();
    }
  });

  // Logo按钮事件
  logoBtn.addEventListener('click', function() {
    chrome.tabs.create({url: baseUrl});
  });
  
  // 收藏当前页面
  bookmarkBtn.addEventListener('click', function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      const currentTab = tabs[0];
      
      // 检查URL是否是chrome://开头，如果是则不尝试获取描述
      if (currentTab.url.startsWith('chrome://') || 
          currentTab.url.startsWith('chrome-extension://') || 
          currentTab.url.startsWith('edge://') || 
          currentTab.url.startsWith('about:')) {
        // 对于Chrome内部页面，直接创建书签而不获取描述
        createBookmarkWithoutDescription(currentTab);
        return;
      }
      
      // 尝试获取网页描述
      try {
        // 使用chrome.scripting.executeScript代替chrome.tabs.executeScript
        chrome.scripting.executeScript({
          target: { tabId: currentTab.id },
          func: function() {
            // 尝试从meta标签获取描述
            let description = document.querySelector("meta[name='description']")?.content || 
                              document.querySelector("meta[property='og:description']")?.content;
            
            // 如果没有meta描述，尝试获取第一段文本
            if (!description) {
              const paragraphs = document.querySelectorAll('p');
              for (let i = 0; i < paragraphs.length; i++) {
                const text = paragraphs[i].textContent.trim();
                if (text && text.length > 20) { // 只获取有意义的段落（至少20个字符）
                  description = text.substring(0, 200) + (text.length > 200 ? '...' : ''); // 限制长度
                  break;
                }
              }
            }
            
            return description || "";
          }
        }).then(results => {
          let description = "";
          if (results && results[0] && results[0].result) {
            description = results[0].result;
          }
            
            // 创建书签
            chrome.bookmarks.create({
              title: currentTab.title,
              url: currentTab.url
            }, function(bookmark) {
              showStatus('成功收藏: ' + currentTab.title, 'success');
              
              // 保存到最近收藏
              saveToRecentBookmarks({
                id: bookmark.id,
                title: bookmark.title,
                url: bookmark.url,
                description: description
              });
              
              // 重新加载最近收藏列表
              loadRecentBookmarks();
            });
          }
        );
      } catch (error) {
        console.error('获取描述失败:', error);
        // 如果获取描述失败，仍然创建书签但没有描述
        createBookmarkWithoutDescription(currentTab);
      }
    });
  });
  
  // 查看所有收藏
  // viewBtn.addEventListener('click', function() {
  //   chrome.tabs.create({url: 'chrome://bookmarks/'});
  // });
  
  // 创建书签但不获取描述的辅助函数
  function createBookmarkWithoutDescription(tab) {
    chrome.bookmarks.create({
      title: tab.title,
      url: tab.url
    }, function(bookmark) {
      showStatus('成功收藏: ' + tab.title, 'success');
      
      // 保存到最近收藏
      saveToRecentBookmarks({
        id: bookmark.id,
        title: bookmark.title,
        url: bookmark.url
      });
      
      // 重新加载最近收藏列表
      loadRecentBookmarks();
    });
  }
  
  // 加载分类下的书签
  function loadCategoryBookmarks(categoryId, bookmarksList) {
    // 从本地获取用户信息和登录状态
    chrome.storage.local.get(['user', 'isLoggedIn'], function(data) {
      if (data.isLoggedIn && data.user && data.user.token) {
        // 从后端获取该分类下的书签数据
        console.log('调用API获取分类详情，categoryId:', categoryId);
        makeRequest(baseUrl + '/auth/getCateDetail', 'POST', {
          categoryId: categoryId
        }, {
          'Authorization': data.user.token
        })
        .then(response => {
          console.log('API响应:', response);
          if (response.code != 200) {
            bookmarksList.innerHTML = '<li class="error-message">获取书签失败</li>';
            return;
          }
          
          const siteData = response.data || [];
          console.log('获取到的书签数据:', siteData);
          
          if (siteData.length === 0) {
            bookmarksList.innerHTML = '<li class="empty-message">此分类下暂无收藏</li>';
            return;
          }
          
          bookmarksList.innerHTML = '';
          
          siteData.forEach(function(site) {
            const bookmarkLi = document.createElement('li');
            bookmarkLi.className = 'bookmark-item';
            bookmarkLi.draggable = true; // 使书签项可拖拽
            bookmarkLi.dataset.siteId = site.id; // 存储书签ID
            bookmarkLi.dataset.currentCategoryId = categoryId; // 存储当前分类ID
            
            const titleSpan = document.createElement('span');
            titleSpan.className = 'bookmark-title';
            
            const link = document.createElement('a');
            link.href = site.addr;
            link.className = 'bookmark-link';
            link.textContent = site.name;
            // 如果有描述，将其添加到title属性中，鼠标悬停时显示
            link.title = site.description ? `${site.name} - ${site.description}` : site.name;
            
            link.addEventListener('click', function(e) {
              e.preventDefault();
              chrome.tabs.create({url: site.addr});
            });
            
            // 为整个书签项添加点击事件（点击空白区域也能跳转）
            bookmarkLi.addEventListener('click', function(e) {
              // 防止点击链接或删除按钮时触发
              if (e.target.tagName !== 'A' && e.target.tagName !== 'BUTTON' && !e.target.classList.contains('delete-btn')) {
                chrome.tabs.create({url: site.addr});
              }
            });
            
            titleSpan.appendChild(link);
            
            // 如果有描述，添加描述元素
            if (site.description) {
              const descSpan = document.createElement('div');
              descSpan.className = 'bookmark-description';
              descSpan.textContent = site.description.length > 100 ? 
                site.description.substring(0, 100) + '...' : site.description;
              titleSpan.appendChild(descSpan);
            }
            
            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'delete-btn';
            deleteBtn.textContent = '×';
            deleteBtn.title = '删除收藏';
            deleteBtn.addEventListener('click', function() {
              // 调用删除API
              deleteBookmark(site.id, function(success) {
                if (success) {
                  // 删除成功后移除DOM节点
                  bookmarkLi.remove();
                  showStatus('已删除收藏', 'success');
                  
                  // 检查是否还有其他书签项
                  const remainingItems = bookmarksList.querySelectorAll('.bookmark-item');
                  if (remainingItems.length === 0) {
                    bookmarksList.innerHTML = '<li class="empty-message">此分类下暂无收藏</li>';
                  }
                } else {
                  showStatus('删除收藏失败', 'error');
                }
              });
            });
            
            // 添加拖拽事件处理
            bookmarkLi.addEventListener('dragstart', function(e) {
              e.dataTransfer.setData('text/plain', JSON.stringify({
                siteId: site.id,
                siteName: site.name,
                currentCategoryId: categoryId
              }));
              bookmarkLi.classList.add('dragging');
              
              // 为所有分类标题添加拖拽目标样式
              document.querySelectorAll('.category-header').forEach(header => {
                if (header.dataset.categoryId !== categoryId) {
                  header.classList.add('drag-target');
                }
              });
            });
            
            bookmarkLi.addEventListener('dragend', function(e) {
              bookmarkLi.classList.remove('dragging');
              
              // 移除所有拖拽目标样式
              document.querySelectorAll('.category-header').forEach(header => {
                header.classList.remove('drag-target', 'drag-over');
              });
            });
            
            bookmarkLi.appendChild(titleSpan);
            bookmarkLi.appendChild(deleteBtn);
            bookmarksList.appendChild(bookmarkLi);
          });
        })
        .catch(error => {
          console.error('获取书签错误:', error);
          bookmarksList.innerHTML = '<li class="error-message">获取书签失败</li>';
        });
      } else {
        bookmarksList.innerHTML = '<li class="error-message">请先登录</li>';
      }
    });
  }
  
  // 显示状态信息
  function showStatus(message, type) {
    // statusDiv.textContent = message;
    // statusDiv.className = 'status ' + type;
    
    // // 3秒后隐藏状态信息
    // setTimeout(function() {
    //   statusDiv.className = 'status';
    // }, 3000);
  }
  
  // 加载最近收藏
  function loadRecentBookmarks() {
    // 从本地获取用户信息和登录状态
    chrome.storage.local.get(['user', 'isLoggedIn'], function(data) {
      if (data.isLoggedIn && data.user && data.user.token) {
        // 从后端获取收藏数据
        makeRequest(baseUrl + '/auth/getCate', 'POST', null, {
          'Authorization': data.user.token
        })
        .then(response => {
          if (response.code != 200) {
            showStatus('获取收藏失败: ' + response.msg, 'error');
            recentBookmarksList.innerHTML = '<li>获取收藏失败</li>';
            return;
          }
          
          const categories = response.data || [];
          
          if (categories.length === 0) {
            // recentBookmarksList.innerHTML = JSON.stringify(response);
            recentBookmarksList.innerHTML = '<li>暂无分类</li>';
            return;
          }
          
          recentBookmarksList.innerHTML = '';
          categories.forEach(function(category) {
            const li = document.createElement('li');
            li.className = 'category-item';
            
            const categoryHeader = document.createElement('div');
            categoryHeader.className = 'category-header';
            categoryHeader.dataset.categoryId = category.id; // 存储分类ID
            
            const categoryTitle = document.createElement('span');
            categoryTitle.className = 'category-title';
            categoryTitle.textContent = category.name || '未命名分类';
            
            // 创建展开/折叠图标
            const toggleIcon = document.createElement('span');
            toggleIcon.className = 'toggle-icon';
            toggleIcon.textContent = '▶';
            
            // 添加拖拽放置事件处理
            categoryHeader.addEventListener('dragover', function(e) {
              e.preventDefault();
              categoryHeader.classList.add('drag-over');
            });
            
            categoryHeader.addEventListener('dragleave', function(e) {
              categoryHeader.classList.remove('drag-over');
            });
            
            categoryHeader.addEventListener('drop', function(e) {
              e.preventDefault();
              categoryHeader.classList.remove('drag-over', 'drag-target');
              
              try {
                const dragData = JSON.parse(e.dataTransfer.getData('text/plain'));
                const { siteId, siteName, currentCategoryId } = dragData;
                
                // 检查是否拖拽到不同的分类
                if (currentCategoryId !== category.id) {
                  // 找到被拖拽的书签元素
                  const draggedElement = document.querySelector(`[data-site-id="${siteId}"]`);
                  moveSiteToCategory(siteId, siteName, currentCategoryId, category.id, category.name, draggedElement);
                }
              } catch (error) {
                console.error('拖拽数据解析失败:', error);
                showStatus('拖拽操作失败', 'error');
              }
            });
            
            categoryHeader.appendChild(toggleIcon);
            categoryHeader.appendChild(categoryTitle);
            
            // 创建书签列表容器
            const bookmarksList = document.createElement('ul');
            bookmarksList.className = 'bookmarks-sublist';
            bookmarksList.style.display = 'none'; // 默认隐藏
            bookmarksList.innerHTML = '<li class="loading-message">加载中...</li>';
            
            // 点击分类标题加载该分类下的书签并展开/折叠
            categoryHeader.addEventListener('click', function() {
              if (bookmarksList.style.display === 'none') {
                // 显示书签列表
                bookmarksList.style.display = 'block';
                toggleIcon.textContent = '▼';
                
                // 加载该分类下的书签
                loadCategoryBookmarks(category.id, bookmarksList);
              } else {
                // 隐藏书签列表
                bookmarksList.style.display = 'none';
                toggleIcon.textContent = '▶';
              }
            });
            
            li.appendChild(categoryHeader);
            li.appendChild(bookmarksList);
            recentBookmarksList.appendChild(li);
          });
        })
        .catch(error => {
          console.error('获取收藏错误:', error);
          recentBookmarksList.innerHTML = '<li>获取收藏失败</li>';
        });
      } else {
        // 如果未登录，显示空数据
        recentBookmarksList.innerHTML = '<li>暂无最近收藏</li>';
      }
    });
  }
  
  // 保存到最近收藏
  function saveToRecentBookmarks(bookmark) {
    // 从本地获取用户信息和登录状态
    chrome.storage.local.get(['user', 'isLoggedIn'], function(data) {
      if (data.isLoggedIn && data.user && data.user.token) {
        // 向后端发送保存收藏请求
        makeRequest(baseUrl + '/auth/saveSite', 'POST', {
          name: bookmark.title,
          addr: bookmark.url,
          description: bookmark.description || "" // 添加描述字段
        }, {
          'Authorization': data.user.token
        })
        .then(response => {
          if (response.code != 200) {
            showStatus('保存收藏失败: ' + response.msg, 'error');
            return;
          }
          
          showStatus('成功保存收藏', 'success');
          // 重新加载收藏列表
          loadRecentBookmarks();
        })
        .catch(error => {
          console.error('保存收藏错误:', error);
          showStatus('保存收藏失败', 'error');
        });
      } else {
        // 如果未登录，使用本地存储
        chrome.storage.local.get('recentBookmarks', function(data) {
          let recentBookmarks = data.recentBookmarks || [];
          
          // 检查是否已存在
          const existingIndex = recentBookmarks.findIndex(b => b.url === bookmark.url);
          if (existingIndex !== -1) {
            recentBookmarks.splice(existingIndex, 1);
          }
          
          // 添加到最前面，包含描述信息
          const bookmarkWithDesc = {
            id: bookmark.id,
            title: bookmark.title,
            url: bookmark.url,
            description: bookmark.description || ""
          };
          
          recentBookmarks.unshift(bookmarkWithDesc);
          
          // 只保留最近10个
          if (recentBookmarks.length > 10) {
            recentBookmarks = recentBookmarks.slice(0, 10);
          }
          
          chrome.storage.local.set({recentBookmarks: recentBookmarks});
        });
      }
    });
  }
  
  // 删除书签（优化版本，支持回调）
  function deleteBookmark(bookmarkId, callback) {
    // 从本地获取用户信息和登录状态
    chrome.storage.local.get(['user', 'isLoggedIn'], function(data) {
      if (data.isLoggedIn && data.user && data.user.token) {
        // 向后端发送删除收藏请求
        makeRequest(baseUrl + '/auth/deleteSite', 'POST', {
          siteId: bookmarkId
        }, {
          'Authorization': data.user.token
        })
        .then(response => {
          if (response.code != 200) {
            callback(false);
            return;
          }
          
          callback(true);
        })
        .catch(error => {
          console.error('删除收藏错误:', error);
          callback(false);
        });
      } else {
        // 如果未登录，使用本地存储
        chrome.storage.local.get('recentBookmarks', function(data) {
          let recentBookmarks = data.recentBookmarks || [];
          recentBookmarks = recentBookmarks.filter(b => b.id !== bookmarkId);
          chrome.storage.local.set({recentBookmarks: recentBookmarks}, function() {
            callback(true);
          });
        });
      }
    });
  }
  
  // 保持向后兼容的删除函数
  function removeFromRecentBookmarks(bookmarkId) {
    deleteBookmark(bookmarkId, function(success) {
      if (success) {
        showStatus('成功删除收藏', 'success');
        // 重新加载收藏列表（保持原有行为）
        loadRecentBookmarks();
      } else {
        showStatus('删除收藏失败', 'error');
      }
    });
  }
  
  // 检查登录状态
  function checkLoginStatus() {
    chrome.storage.local.get(['user', 'isLoggedIn'], function(data) {
      if (data.isLoggedIn && data.user) {
        showMainInterface(data.user.username);
      } else {
        showLoginInterface();
      }
    });
  }
  
  // 显示登录界面
  function showLoginInterface() {
    loginSection.style.display = 'block';
    mainSection.style.display = 'none';
    usernameInput.value = '';
    passwordInput.value = '';
    loginStatus.textContent = '';
    loginStatus.className = 'status';
  }
  
  // 显示主界面
  function showMainInterface(username) {
    loginSection.style.display = 'none';
    mainSection.style.display = 'block';
    userWelcome.textContent = `欢迎，${username}`;
    
    // 加载最近收藏
    loadRecentBookmarks();
    

  }
  
  // 登录功能
  function login(username, password) {
    showLoginStatus('正在登录...', 'loading');
    
    // 调用通用请求方法
    makeRequest(baseUrl + '/auth/login', 'POST', {
      username: username,
      password: password
    })
    .then(data => {
      if(data.code != 200){
        showLoginStatus(data.msg, 'error');
        return;
      }

      // 登录成功
      const user = {
        username: username,
        loginTime: new Date().toISOString(),
        token: data.msg || null // 假设API返回token
      };
      
      chrome.storage.local.set({
        user: user,
        isLoggedIn: true
      }, function() {
        showLoginStatus('登录成功', 'success');
        setTimeout(() => {
          showMainInterface(username);
        }, 1000);
      });
    })
    .catch(error => {
      console.error('登录错误:', error);
      showLoginStatus(error.message || '登录失败', 'error');
    });
  }
  
  // 注册功能
  function register(username, password) {
    showLoginStatus('正在注册...', 'loading');
    
    // 调用通用请求方法
    makeRequest(baseUrl + '/auth/register', 'POST', {
      username: username,
      password: password
    })
    .then(data => {
      if(data.code != 200){
        showLoginStatus(data.msg, 'error');
        return;
      }
      
      // 注册成功后自动登录
      const user = {
        username: username,
        loginTime: new Date().toISOString(),
        token: data.msg || null
      };
      
      chrome.storage.local.set({
        user: user,
        isLoggedIn: true
      }, function() {
        showLoginStatus('注册成功', 'success');
        setTimeout(() => {
          showMainInterface(username);
        }, 1000);
      });
    })
    .catch(error => {
      console.error('注册错误:', error);
      showLoginStatus(error.message || '注册失败', 'error');
    });
  }
  
  // 退出功能
  function logout() {
    chrome.storage.local.get(['user', 'isLoggedIn'], function(data) {
      if (data.isLoggedIn && data.user) {
        // 调用通用请求方法
        makeRequest(baseUrl + '/auth/logout', 'POST', null, {
          'Authorization': data.user.token
        })
        .then(data => {
          if(data.code != 200){
            showLoginStatus(data.msg, 'error');
            return;
          }

          chrome.storage.local.set({
            isLoggedIn: false,
            user: null
          }, function() {
            showLoginInterface();
          });
        })
        .catch(error => {
          console.error('退出失败', error);
        });
      } 
    });
  }
  
  // 移动书签到其他分类
  function moveSiteToCategory(siteId, siteName, fromCategoryId, toCategoryId, toCategoryName, draggedElement) {
    chrome.storage.local.get(['user', 'isLoggedIn'], function(data) {
      if (data.isLoggedIn && data.user && data.user.token) {
        showStatus('正在移动书签...', 'loading');
        
        // 调用后端API移动书签
        makeRequest(baseUrl + '/auth/moveSite', 'POST', {
          siteId: siteId,
          fromCategoryId: fromCategoryId,
          toCategoryId: toCategoryId
        }, {
          'Authorization': data.user.token
        })
        .then(response => {
          if (response.code !== 200) {
            showStatus('移动书签失败: ' + response.msg, 'error');
            return;
          }
          
          showStatus(`已将"${siteName}"移动到"${toCategoryName}"`, 'success');
          
          // 手动更新DOM：从源分类移除书签
          if (draggedElement) {
            const sourceBookmarksList = draggedElement.parentElement;
            draggedElement.remove();
            
            // 检查源分类是否为空
            const remainingItems = sourceBookmarksList.querySelectorAll('.bookmark-item');
            if (remainingItems.length === 0) {
              sourceBookmarksList.innerHTML = '<li class="empty-message">此分类下暂无收藏</li>';
            }
          }
          
          // 添加短暂延迟后刷新目标分类，确保后端数据已更新
          setTimeout(() => {
            refreshCategoryBookmarks(toCategoryId, true);
          }, 300);
        })
        .catch(error => {
          console.error('移动书签错误:', error);
          showStatus('移动书签失败', 'error');
        });
      } else {
        showStatus('请先登录', 'error');
      }
    });
  }
  
  // 刷新特定分类的书签列表
  function refreshCategoryBookmarks(categoryId, forceRefresh = false) {
    console.log('刷新分类:', categoryId, '强制刷新:', forceRefresh);
    
    // 找到对应的书签列表容器
    const categoryHeaders = document.querySelectorAll('.category-header');
    let targetBookmarksList = null;
    let targetHeader = null;
    
    categoryHeaders.forEach(header => {
      if (header.dataset.categoryId == categoryId) { // 使用 == 而不是 === 来处理类型转换
        targetHeader = header;
        // 找到对应的书签列表
        targetBookmarksList = header.parentElement.querySelector('.bookmarks-sublist');
      }
    });
    
    console.log('找到目标分类:', !!targetBookmarksList, '当前显示状态:', targetBookmarksList?.style.display);
    
    if (targetBookmarksList && targetHeader) {
      // 如果强制刷新或分类已展开，则刷新书签列表
      if (forceRefresh || targetBookmarksList.style.display !== 'none') {
        
        // 如果是强制刷新且分类未展开，先展开它
        if (forceRefresh && targetBookmarksList.style.display === 'none') {
          targetBookmarksList.style.display = 'block';
          // 更新展开图标
          const toggleIcon = targetHeader.querySelector('.toggle-icon');
          if (toggleIcon) {
            toggleIcon.textContent = '▼';
          }
          console.log('展开目标分类');
        }
        
        targetBookmarksList.innerHTML = '<li class="loading-message">加载中...</li>';
        console.log('开始加载分类书签');
        loadCategoryBookmarks(categoryId, targetBookmarksList);
      }
    } else {
      console.log('未找到目标分类或书签列表');
    }
  }
  
  // 显示登录状态
  function showLoginStatus(message, type) {
    loginStatus.textContent = message;
    loginStatus.className = 'status ' + type;
    
    if (type !== 'loading') {
      setTimeout(function() {
        loginStatus.className = 'status';
      }, 10000);
    }
  }
  
  // 初始化标签页切换功能
  function initTabs() {
    if (tabBookmarks && tabClosedTabs) {
      tabBookmarks.addEventListener('click', function() {
        switchTab('bookmarks');
      });
      
      tabClosedTabs.addEventListener('click', function() {
        switchTab('closedTabs');
      });
    }
  }
  
  // 切换标签页
  function switchTab(tabName) {
    // 移除所有标签页的激活状态
    tabBookmarks?.classList.remove('active');
    tabClosedTabs?.classList.remove('active');
    tabBookmarksContent?.classList.remove('active');
    tabClosedTabsContent?.classList.remove('active');
    
    // 激活选中的标签页
    if (tabName === 'bookmarks') {
      tabBookmarks?.classList.add('active');
      tabBookmarksContent?.classList.add('active');
    } else if (tabName === 'closedTabs') {
      tabClosedTabs?.classList.add('active');
      tabClosedTabsContent?.classList.add('active');
      
      // 切换到最近关闭标签页时加载数据
      loadRecentClosedTabs();
    }
  }
  
  // 加载最近关闭的标签页
  function loadRecentClosedTabs() {
    if (!recentClosedTabsList) return;
    
    // 显示加载状态
    recentClosedTabsList.innerHTML = '<li class="loading-message">加载中...</li>';
    
    // 使用Chrome API获取最近关闭的标签页
    if (chrome.sessions && chrome.sessions.getRecentlyClosed) {
      chrome.sessions.getRecentlyClosed(function(sessions) {
        if (chrome.runtime.lastError) {
          console.error('获取最近关闭标签页失败:', chrome.runtime.lastError);
          recentClosedTabsList.innerHTML = '<li class="empty-message">获取最近关闭标签页失败</li>';
          return;
        }
        
        // 过滤出标签页会话
        const tabSessions = sessions.filter(session => session.tab);
        
        if (tabSessions.length === 0) {
          recentClosedTabsList.innerHTML = '<li class="empty-message">暂无最近关闭的标签页</li>';
          return;
        }
        
        // 清空列表
        recentClosedTabsList.innerHTML = '';
        
        // 显示最近关闭的标签页（最多显示10个）
        tabSessions.slice(0, 10).forEach(function(session, index) {
          const tab = session.tab;
          const closedTabLi = document.createElement('li');
          closedTabLi.className = 'closed-tab-item';
          
          // 创建标题和URL显示（不换行，超过隐藏）
          const contentDiv = document.createElement('div');
          contentDiv.className = 'closed-tab-content';
          
          const titleSpan = document.createElement('span');
          titleSpan.className = 'closed-tab-title';
          titleSpan.textContent = tab.title || '无标题';
          
          const urlSpan = document.createElement('span');
          urlSpan.className = 'closed-tab-url';
          urlSpan.textContent = tab.url || '无URL';
          
          contentDiv.appendChild(titleSpan);
          contentDiv.appendChild(urlSpan);
          
          closedTabLi.appendChild(contentDiv);
          
          // 添加点击事件 - 点击整个标签项跳转到链接
          closedTabLi.addEventListener('click', function() {
            if (tab.url) {
              // 使用tabs API创建新标签页跳转到链接
              chrome.tabs.create({url: tab.url}, function(newTab) {
                if (chrome.runtime.lastError) {
                  console.error('创建标签页失败:', chrome.runtime.lastError);
                  showStatus('创建标签页失败', 'error');
                } else {
                  showStatus('已打开标签页', 'success');
                  window.close();
                }
              });
            } else {
              showStatus('无法打开链接：URL为空', 'error');
            }
          });
          
          recentClosedTabsList.appendChild(closedTabLi);
        });
      });
    } else {
      // 如果sessions API不可用，显示提示信息
      recentClosedTabsList.innerHTML = '<li class="empty-message">当前浏览器不支持最近关闭标签页功能</li>';
    }
  }
  
  // 如果logo元素存在，添加点击事件
  if (logoBtn) {
    logoBtn.addEventListener('click', function() {
      if (typeof window.handleLogoClick === 'function') {
        window.handleLogoClick();
      }
    });
  }
});